package com.macro.mall.tiny.modules.ums.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.modules.ums.mapper.GroupMapper;
import com.macro.mall.tiny.modules.ums.model.Group;
import com.macro.mall.tiny.modules.ums.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author tuouren
 * @description 针对表【tb_grade_group(小组表)】的数据库操作Service实现
 * @createDate 2022-03-24 14:11:45
 */
@Service
public class GroupServiceImpl extends ServiceImpl<GroupMapper, Group>
        implements GroupService {


    @Autowired
    private GroupMapper groupMapper;

    @Override
    public List<Group> listGroupName() {
        QueryWrapper<Group> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DISTINCT groupname, id,ration");
        return this.list(queryWrapper);
    }

    @Override
    public int updateRation(List<Group> group) {
        group.forEach(e -> {
            this.update(new UpdateWrapper<Group>()
                    .set("ration", e.getRation())
                    .set("update_time", new Date())
                    .eq("groupname", e.getGroupname()));
        });
        return 1;
    }

    @Override
    @Transactional
    public Group saveGroup(Group group) {
        if (group.getGroupname() != null && group.getRation() != null) {
            group.setCreateTime(new Date())
                    .setUpdateTime(new Date());
            save(group);
        }

        return group;
    }

    @Override
    public Group getGroup(String username) {
        return groupMapper.getGroup(username);
    }

    @Override
    public boolean deleteGroupByName(String name) {
        if (name != null) {
            UpdateWrapper wrapper = new UpdateWrapper<Group>();
            wrapper.eq("groupname", name);
            return this.remove(wrapper);
        }
        return false;
    }
}
